//
//  loginViewController.m
//  theCoupleLive
//
//  Created by USER on 2016/12/2.
//  Copyright © 2016年 USER. All rights reserved.
//

#import "loginViewController.h"
#import "changePwdViewController.h"
#import "coupleLiveAPI.h"
#import "MainViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "AppDelegate.h"

#define APPDELEGATE ((AppDelegate*)[[UIApplication sharedApplication] delegate])

@interface loginViewController ()<changePwdDelegate,CLLocationManagerDelegate>
@property(nonatomic,assign)int flog;
@property(nonatomic,strong)CLLocationManager *locationManager;
@property(nonatomic,copy)NSString *longitude;
@property(nonatomic,copy)NSString *latitude;
@property(nonatomic,copy)NSString *location;//定位
@property(nonatomic,copy)NSString *city;//城市
@end

@implementation loginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.btn_login.layer.masksToBounds=YES;
    self.btn_login.layer.cornerRadius=8;
    self.navigationController.navigationBarHidden=YES;
    self.password.secureTextEntry = YES;
    self.flog=0;
    self.location=@"31.984609,120.910702";
    self.city=@"";
    //初始化定位管理器
//    [self initializeLocationService];
    // Do any additional setup after loading the view from its nib.
}

#pragma mark 判断睁眼闭眼
- (IBAction)closeAndOpenEyes:(UIButton *)sender {
    if (self.flog==0) {
        [self.openeyes  setImage:[UIImage imageNamed:@"biyan"] forState:UIControlStateNormal];
        self.password.secureTextEntry = NO;
        self.flog=1;
    }
    else{
        [self.openeyes setImage:[UIImage imageNamed:@"zhengyan"] forState:UIControlStateNormal];
        self.password.secureTextEntry=YES;
        self.flog=0;
    }
}

-(void)changePwdWithName:(NSString *)name password:(NSString *)password{
    self.telephonenum.text=name;
    self.password.text=password;
}

#pragma mark 忘记密码
- (IBAction)btn_forgetPwd:(UIButton *)sender {
    changePwdViewController *chg=[[changePwdViewController alloc]initWithNibName:@"changePwdViewController" bundle:[NSBundle mainBundle]];
    chg.telnum=self.telephonenum.text;
    chg.delegate=self;
    [self.navigationController pushViewController:chg animated:YES];
}

#pragma mark 定位管理器
- (void)initializeLocationService {
    // 初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    // 开始定位
    // 取得定位权限，有两个方法，取决于你的定位使用情况
    // 一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
    [_locationManager requestAlwaysAuthorization];//这句话ios8以上版本使用。
    [_locationManager startUpdatingLocation];
}

#pragma mark 定位
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //将经度显示到label上
    self.longitude = [NSString stringWithFormat:@"%lf", newLocation.coordinate.longitude];
    //将纬度现实到label上
    self.latitude = [NSString stringWithFormat:@"%lf", newLocation.coordinate.latitude];
    self.location=[NSString stringWithFormat:@"%@,%@",self.latitude,self.longitude];
//    NSLog(@"%@",self.location);
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //将获得的所有信息显示到label上
//            self.location = placemark.name;
//            NSLog(@"%@",self.location);
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            self.city=city;
            
            //跳转处理登陆数据
            [self loginAPI];
            
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
}

#pragma mark 登录
- (IBAction)login:(UIButton *)sender {
    [self initializeLocationService];
}

#pragma mark 登陆api
-(void)loginAPI{
    
    [coupleLiveAPI loginLiveWithName:self.telephonenum.text pwd:self.password.text u_address:self.city u_gps:self.location success:^(id response) {
        if ([[NSString stringWithFormat:@"%@",[[response allKeys] objectAtIndex:0]]isEqualToString:@"uid"]) {
            //            [self alert:@"登录成功"];
            [APPDELEGATE addID:[response objectForKey:@"uid"] usergps:self.location];
//            NSLog(@"%@,gps:%@",[response objectForKey:@"uid"],self.location);
            [self loginOSChina];
        }
        else if ([[NSString stringWithFormat:@"%@",[[response allKeys] objectAtIndex:0]]isEqualToString:@"u_feng_time"]) {
            [self alertFail:[NSString stringWithFormat:@"当前用户被封号，解封时间为%@",[response objectForKey:@"u_feng_time"]]];
        }
        else{
            [self alertFail:@"账号或密码错误"];
        }
    }];
}

#pragma mark 登陆跳转
-(void)loginOSChina{
    MainViewController *mainVC=[[MainViewController alloc]init];
    [self presentViewController:mainVC animated:YES completion:nil];
}

#pragma mark  失败alther弹窗
-(void)alertFail:(NSString *)mes{
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"提示:" message:mes preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    
    [controller addAction:action1];
    
    [self presentViewController:controller animated:YES completion:nil];
    
}

#pragma mark 点击空白位置键盘隐藏
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.telephonenum resignFirstResponder];
    [self.password resignFirstResponder];
    //textView键盘隐藏
    //[textView resignFirstResponder];
}
- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
